import AntModal from "@/components/pt/dialog/AntModal";
import {
  getBizXiansuoChengben,
  addBizXiansuoChengben,
  updateBizXiansuoChengben,
  findMaxSort,
  findExist,
  addBatch,
} from "@/api/biz/bizXiansuoChengben";

export default {
  name: "CreateForm",
  props: {
    laiyuanOptions: {
      type: Array,
      required: true,
    },
    cityOptions: {
      type: Array,
      required: true,
    },
    laiyuanType: {
      type: String,
      required: true,
    },
  },
  components: {
    AntModal,
  },
  data() {
    return {
      open: false,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      loading: false,
      total: 0,
      id: undefined,
      formTitle: "添加线索成本设置",
      // 表单参数
      form: {},
      rules: {},
      // 来源穿梭框数据源
      laiyuanData: [],
      targetLaiyuanKeys: [],
      // 城市穿梭框数据源
      cityData: [],
      targetCityKeys: [],
      // 列表的数据源
      tableData: [],
      defaultPrice: undefined,
      columns: [
        {
          title: "来源",
          dataIndex: "laiyuan",
          ellipsis: true,
          align: "center",
          width: "80px",
        },
        {
          title: "城市",
          dataIndex: "city",
          ellipsis: true,
          align: "center",
          width: "100px",
        },
        {
          title: "成本金额（元/条）",
          dataIndex: "amount",
          ellipsis: true,
          align: "center",
          width: "80px",
          scopedSlots: { customRender: "amount" },
        },
        {
          title: "备注",
          dataIndex: "remark",
          ellipsis: true,
          align: "center",
          width: "200px",
          scopedSlots: { customRender: "remark" },
        },
      ],
    };
  },
  filters: {},
  created() {},
  computed: {},
  watch: {},
  mounted() {},
  methods: {
    getLaiyuanMock() {
      const targetKeys = [];
      const mockData = [];
      const options = this.laiyuanOptions;
      for (let i = 0; i < options.length; i++) {
        const data = {
          key: options[i].dictValue,
          title: options[i].dictLabel,
          // chosen: Math.random() * 2 > 1,
        };
        if (data.chosen) {
          targetKeys.push(data.key);
        }
        mockData.push(data);
      }
      this.laiyuanData = mockData;
      this.targetLaiyuanKeys = targetKeys;
    },
    getCityMock() {
      const targetKeys = [];
      const mockData = [];
      const options = this.cityOptions;
      for (let i = 0; i < options.length; i++) {
        const data = {
          key: options[i].name,
          title: options[i].name,
          // chosen: Math.random() * 2 > 1,
        };
        if (data.chosen) {
          targetKeys.push(data.key);
        }
        mockData.push(data);
      }
      this.cityData = mockData;
      this.targetCityKeys = targetKeys;
    },
    handleChangeLaiyuan(targetKeys, direction, moveKeys) {
      this.targetLaiyuanKeys = targetKeys;
      this.getTableData("laiyuan", targetKeys, direction, moveKeys);
    },
    handleChangeCity(targetKeys, direction, moveKeys) {
      this.targetCityKeys = targetKeys;
      this.getTableData("city", targetKeys, direction, moveKeys);
    },

    getTableData(from, targetKeys, direction, moveKeys) {
      const tableData = this.tableData;
      const price = this.defaultPrice;

      if (from === "laiyuan") {
        const city = this.targetCityKeys;
        for (let i = 0; i < moveKeys.length; i++) {
          for (let j = 0; j < city.length; j++) {
            const data = {
              rowid: moveKeys[i] + city[j],
              laiyuan: moveKeys[i],
              city: city[j].replace("市", ""),
              amount: price,
              laiyuanType: this.laiyuanType,
            };
            if (direction === "right") {
              if (
                tableData.filter((item) => item.rowid === data.rowid).length ===
                0
              ) {
                this.tableData.push(data);
              }
            } else if (direction === "left") {
              this.tableData = tableData.filter(
                (item) => item.laiyuan !== data.laiyuan
              );
            }
          }
        }
      } else if (from === "city") {
        const laiyuan = this.targetLaiyuanKeys;
        for (let i = 0; i < moveKeys.length; i++) {
          for (let j = 0; j < laiyuan.length; j++) {
            const data = {
              rowid: laiyuan[j] + moveKeys[i],
              laiyuan: laiyuan[j],
              city: moveKeys[i].replace("市", ""),
              amount: price,
              laiyuanType: this.laiyuanType,
            };
            if (direction === "right") {
              if (
                tableData.filter((item) => item.rowid === data.rowid).length ===
                0
              ) {
                this.tableData.push(data);
              }
            } else if (direction === "left") {
              this.tableData = tableData.filter(
                (item) => item.city !== data.city
              );
            }
          }
        }
      }
    },
    onChangePrice(value) {
      this.tableData = this.tableData.map((item) => ({
        ...item,
        // 将列表单价默认值改为默认单价
        amount: value,
      }));
    },
    onClose() {
      this.open = false;
      this.reset();
      this.$emit("close");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$emit("close");
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        amount: undefined,

        laiyuan: undefined,

        city: undefined,

        sort: undefined,

        status: undefined,

        remark: undefined,

        laiyuanType: undefined,
      };
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getLaiyuanMock();
      this.getCityMock();
      this.open = true;
      /** 获取最大编号 */
      findMaxSort().then((response) => {
        this.form.sort = response.data;
        this.formTitle = "添加线索成本设置";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.spinning = !this.spinning;
      const bizXiansuoChengbenId = row.id;
      getBizXiansuoChengben(bizXiansuoChengbenId).then((response) => {
        this.form = response.data;
        this.formTitle = "修改线索成本设置";
        this.spinning = !this.spinning;
      });
    },

    submitTransferForm() {
      addBatch(this.tableData).then((response) => {
        this.$message.success("新增成功", 3);
        this.open = false;
        this.$emit("ok");
        this.$emit("close");
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const saveForm = JSON.parse(JSON.stringify(this.form));
          saveForm.laiyuanType = this.laiyuanType;

          findExist(saveForm).then((response) => {
            const exist = response.data;
            if (exist != null) {
              this.$message.warning("同一城市同一线索不能重复设置", 3);
            } else {
              if (this.form.id !== undefined) {
                updateBizXiansuoChengben(saveForm).then((response) => {
                  this.$message.success("修改成功", 3);
                  this.open = false;
                  this.$emit("ok");
                  this.$emit("close");
                });
              } else {
                addBizXiansuoChengben(saveForm).then((response) => {
                  this.$message.success("新增成功", 3);
                  this.open = false;
                  this.$emit("ok");
                  this.$emit("close");
                });
              }
            }
          });
        } else {
          return false;
        }
      });
    },
    back() {
      const index = "/biz/xiansuochengben/index";
      this.$router.push(index);
    },
  },
};
